package com.chii.colorization.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.chii.colorization.R;
import com.chii.colorization.ui.adapter.ColorAdapter;
import com.chii.colorization.utils.GlideEngine;
import com.chii.colorization.utils.SPUtil;
import com.chii.colorization.utils.connes.MyUrl;
import com.chii.colorization.utils.connes.OkHttpUtil;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ColorizationActivity extends AppCompatActivity {

    @BindView(R.id.color_listView)
    ListView colorListView;
    @BindView(R.id.fab_add)
    FloatingActionButton fabAdd;
    private Handler mHandler;
    private List<HashMap<String, Object>> imageList;
    private Snackbar snackbar;


    private JSONObject token;
    private Boolean vip;
    private int count;

    private ColorAdapter colorAdapter;
    private static String defInput, defOutput;
    private static final int INIT = 0;

    private static final int UPDATE = 1;
    private static final int DELETE = 2;
    private static final int GET_HISTORY = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_colorization);
        ButterKnife.bind(this);
        //初始化返回按键
        initAction();
        initHandler();
        initData();
        initList();

    }

    private void initAction() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    private void initData() {
        vip = (Boolean) SPUtil.get(ColorizationActivity.this, "vip", Boolean.FALSE);

        imageList = new ArrayList<>();
        String config = (String) SPUtil.get(this, "config", "");
        JSONObject jsonObject = (JSONObject) JSON.parse(config);
        //color
        JSONObject welcome = jsonObject.getJSONObject("colorization").getJSONObject("welcome");
        defInput = welcome.getString("input");
        defOutput = welcome.getString("output");
        token = JSONObject.parseObject((String) SPUtil.get(ColorizationActivity.this, "token", ""));

        String colorCount = (String) SPUtil.get(ColorizationActivity.this, "colorCount", "");
        //初始化限制
        if ("".equals(colorCount)) {
            saveCount(0);
        }
        Timer timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = GET_HISTORY;
                mHandler.sendMessage(message);
            }
        };
        //主线程中调用，定时刷新历史记录：
        timer.schedule(timerTask, 1000, 10000);//延时1s，每隔500毫秒执行一次run方法
    }

    /**
     * 处理列表的点击
     */
    private void initList() {
        colorAdapter = new ColorAdapter(this, imageList);
        colorListView.setAdapter(colorAdapter);
        colorListView.setSelection(colorAdapter.getCount() - 1);

        colorListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<String> urls = new ArrayList<>();
                urls.add(imageList.get(position).get("input").toString());
                urls.add(imageList.get(position).get("output").toString());

                Intent intent = new Intent();
                intent.putStringArrayListExtra("urls", urls);
                intent.setClass(ColorizationActivity.this, PhotoActivity.class);
                startActivity(intent);
            }
        });
        colorListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                final String[] items = new String[]{"删除该条历史记录"};
                AlertDialog dialog = new AlertDialog.Builder(ColorizationActivity.this)
                        .setItems(items, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int pos) {
                                deleteHistory(imageList.get(i).get("id").toString());
                                imageList.remove(i);
                                colorAdapter.notifyDataSetChanged();
                            }
                        }).create();

                dialog.show();
                return true;
            }
        });
    }


    private void initHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case INIT:
                        JSONArray jsonArray = (JSONArray) msg.obj;
                        jsonArray.forEach(o -> {
                            JSONObject jsonObject = (JSONObject) o;
                            imageList.add(JSONObject.parseObject(jsonObject.toJSONString(),
                                    new TypeReference<HashMap<String, Object>>() {
                                    }));
                        });
                        //若没有历史则加载默认
                        if (imageList.size() == 0) {
                            HashMap<String, Object> map = new HashMap<>();
                            map.put("input", defInput);
                            map.put("output", defOutput);
                            imageList.add(map);
                        }
                        colorAdapter.notifyDataSetChanged();
                        //自动最下显示
                        colorListView.setSelection(colorAdapter.getCount() - 1);

                        break;
                    case UPDATE:
                        //添加限制记录
                        saveCount(count + 1);
                        int delayNum = (int) msg.obj;
                        snackbar = Snackbar.make(colorListView, "正在渲染图片，请等待"+delayNum/3+"秒", Snackbar.LENGTH_LONG).setAction("Action", null);
                        snackbar.show();
                        break;
                    case DELETE:

                        break;
                    case GET_HISTORY:
                        snackbar = Snackbar.make(colorListView, "正在刷新", Snackbar.LENGTH_SHORT).setAction("Action", null);
                        snackbar.show();
                        getHistory();
                        break;
                    case 500:
                        Intent intent = new Intent();
                        intent.setClass(ColorizationActivity.this, LoginActivity.class);
                        Toast.makeText(ColorizationActivity.this, "无法使用！！", Toast.LENGTH_SHORT).show();
                        startActivity(intent);

                    default:
                }
                return false;
            }
        });
    }

    private boolean limitCount() {
        String colorCount = (String) SPUtil.get(ColorizationActivity.this, "colorCount", "");
        JSONObject jsonObject = JSON.parseObject(colorCount);
        count = jsonObject.getInteger("count");
        String time = jsonObject.getString("time");
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");
        String format = dateFormat.format(new Date());
        //当天
        if (format.equals(time) && count > 10 && !vip) {
            Toast.makeText(ColorizationActivity.this, "您不是会员且今天使用超过10次，请明天再用！！", Toast.LENGTH_LONG).show();
            return true;
        }
        return false;
    }

    private void saveCount(Integer c) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd");
        String format = dateFormat.format(new Date());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("count", c);
        jsonObject.put("time", format);
        SPUtil.put(ColorizationActivity.this, "colorCount", jsonObject.toJSONString());
    }

    @OnClick({R.id.fab_add})
    public void onViewClicked(View view) {
        //限制每天使用次数
        if (limitCount()) {
            return;
        }
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .isCamera(true)
                // 单选
                .selectionMode(PictureConfig.SINGLE)
                .isSingleDirectReturn(true)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .previewImage(true)
                // 是否裁剪
                .enableCrop(true)
                // 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                // 裁剪框是否可拖拽 true or false
                .freeStyleCropEnabled(true)
                // 是否显示uCrop工具栏，默认不显示
                .hideBottomControls(false)
                // 裁剪输出质量 默认100
                .cutOutQuality(90)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                // 是否压缩
                .compress(true)
//                        .forResult(PictureConfig.CHOOSE_REQUEST);
                .forResult(result -> {
                    // Callback方式返回结果...
                    String photoPath = result.get(0).getCompressPath();
                    File file = new File(photoPath);
                    uploadImage(file);

                });
    }

    private void getHistory() {
        //获取历史记录
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        String saveUsername = (String) SPUtil.get(ColorizationActivity.this, "username", "");
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        okHttpUtil.get(MyUrl.history, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
                JSONObject jsonObject = (JSONObject) JSON.parse(s);
                int code = jsonObject.getInteger("code");
                if (code == 200) {
                    JSONArray imageArray = jsonObject.getJSONArray("data");
                    Message message = new Message();
                    message.what = INIT;
                    message.obj = imageArray;
                    mHandler.sendMessage(message);
                } else if (code == 500) {
                    Message message = new Message();
                    message.what = 500;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 500;
                mHandler.sendMessage(message);
            }
        });
    }


    private void uploadImage(File file) {
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        String saveUsername = (String) SPUtil.get(ColorizationActivity.this, "username", "");
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        okHttpUtil.postImage(MyUrl.imageUpload, map, file, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
                JSONObject jsonObject = (JSONObject) JSON.parse(s);
                int code = jsonObject.getInteger("code");
                if (code == 200) {
                    int num = jsonObject.getInteger("data");
                    Message message = new Message();
                    message.what = UPDATE;
                    message.obj = num;
                    mHandler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.what = 500;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 500;
                mHandler.sendMessage(message);
            }
        });
    }


    private void deleteHistory(String id) {
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        String saveUsername = (String) SPUtil.get(ColorizationActivity.this, "username", "");
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        map.put("historyId", id);
        okHttpUtil.delete(MyUrl.history, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
            }

            @Override
            public void failed(IOException e) {
            }
        });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}
